# -*- coding: utf-8 -*-

import webapp2
import json
from google.appengine.ext import db
from google.appengine.api import urlfetch

API_KEY = "AIzaSyD7HPpUsb7SXUB08scyFo2u0TuAe0xtRHc"

class Location:
  lat = None
  long = None

class LocationService:
  langs = {"hebrew": "iw"}

  def getNearBy(self, location, radius=500, types=None):
    """
    location - location with latitude and longitude
    radius - default is 500
    types - an array of types, default - all
    """
    def getUrl(location, radius, types):
      params = {
          "lat": location.lat,
          "long": location.long,
          "radius": radius,
          "lang": self.langs['hebrew'],
          "key": API_KEY,
        }
        
      url = "https://maps.googleapis.com/maps/api/place/search/json?location=%(lat)s,%(long)s&radius=%(radius)s&sensor=false&language=%(lang)s&key=%(key)s" % params
      if types:
        url += "&types=" + ",".join(types)
      return url


    url = getUrl(location, radius, types)
    result = urlfetch.fetch(url)
    if result.status_code == 200:
      res = json.loads(result.content)
      if res['status'] == 'OK': # got data
        if len(res['results']) > 0: # have results
          return res['results']
    # any other case
    return []
      
  def translateCategoryType(catergory):
    """
    given our category returns a single google category or a list of categories
    """
    trans = {
        "חניות נכים" : "parking",
        "כספומטים נגישים" : "atm",
        "מקומות לינה – מלונות וצימרים" : "lodging",
        "פארקים, פינות פיקניק, גנים לאומיים ותצפיות" : "park",
        "אטרקציות" : "museum, stadium, zoo",
        "אולמות קולנוע, תרבות ומופעים" : "movie_theater",
        "מסעדות" : "restaurant",
        "בתי קפה" : "cafe",
        "ברים ומועדונים" : "bar",
        "תחנות דלק" : "gas_station",
        "סניפי בנק וכספומטים" : "bank",
        "קניונים" : "shopping_mall",
        "אולמות ואיצטדיוני ספורט" : "gym",
        "שירותי ממשל" : "local_government_office",
    }
    return trans.get(category, None)
    # still didn't find types for these:
    # "שרותי נכים"
    # "לולאות השראה"
    # "ציוד ואביזרי נכים"
    # "אחר"
    # "חופים"

  def getiAdditionalData(self, ref):
    def getUrl(ref):
      params = {
          'ref': ref,
          'key': API_KEY,
          'lang': self.langs['hebrew'],
        }
      url = "https://maps.googleapis.com/maps/api/place/details/json?reference=%(ref)s&key=%(key)s&sensor=false&language=%(lang)s" % params
      return url
    
    result = urlfetch.fetch(get_url(ref))
    if result.status_code == 200:
      res = json.loads(result.content)
      if res['status'] == "OK":
        return res['result']
    return []

  def getAddress(self, ref):
    return self.get_additional_data(ref)['formatted_address'] # we also have a phone number "formatted_phone_number"

